import {reactive} from 'vue';
import {defineStore} from 'pinia';
import {getAuthInfo, login} from '@/api/user';
import {setToken,setRefreshToken, removeRefreshToken,removeToken} from '@/utils/auth';
export const useUserStore = defineStore('user',()=>{
    const state = reactive({
        token:'',
        refreshToken:'',
        userInfo:null,//当前登录的用户信息
        roles:null//当前登录的用户的角色数组
    });
    const toLogin = async (loginInfo)=>{
        try{
           const response =  await login(loginInfo);
           const {token,refreshToken} = response.data;
           setToken(token);
           setRefreshToken(refreshToken);
           state.token = token;//把token存到仓库里面去
           state.refreshToken=refreshToken;
        }catch(error){
            console.log(error)
        }
    }
    const toLogout = ()=>{
        state.token = '';
        state.refreshToken = '';
        removeToken();
        removeRefreshToken();
    }
    const getUserInfo = async ()=>{
        const result = await getAuthInfo();
        const {roles,...userInfo} = result.data;
        state.userInfo = userInfo;
        state.roles = roles;
    }
    return {
        state,
        toLogin,
        toLogout,
        getUserInfo
    }
})